<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Model\ChKeywordTagScheme;
use Mine\Abstracts\AbstractMapper;
use Mine\Annotation\Transaction;

class ChKeywordTagSchemeMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChKeywordTagScheme::class;
    }

    #[Transaction]
    public function save(array $data): mixed
    {
        $keywords = json_decode($data['keywords'],true);
        $corpTagIds = json_decode($data['corp_tag_ids'],true);
        $smartTagIds = json_decode($data['smart_tag_ids'],true);
        $this->filterExecuteAttributes($data);
        /** @var ChKeywordTagScheme $scheme */
        $scheme = $this->model::create($data);
        $keywords = array_map(function ($item){
            return ['keyword'=>$item];
        },$keywords);
        $scheme->keywords()->createMany($keywords);
        empty($corpTagIds) || $scheme->corpTags()->sync($corpTagIds, false);
        empty($smartTagIds) || $scheme->smartTags()->sync($smartTagIds, false);
        return $scheme->id;
    }

    #[Transaction]
    public function update(mixed $id, array $data): bool
    {
        $keywords = json_decode($data['keywords'],true);
        $corpTagIds = json_decode($data['corp_tag_ids'],true);
        $smartTagIds = json_decode($data['smart_tag_ids'],true);
        $this->filterExecuteAttributes($data, true);

        $this->model::query()->where('id', $id)->update($data);

        /** @var ChKeywordTagScheme $scheme */
        $scheme = $this->model::find($id);
        if ($scheme) {
            $scheme->keywords()->delete();
            $keywords = array_map(function ($item){
                return ['keyword'=>$item];
            },$keywords);
            $scheme->keywords()->createMany($keywords);
            if (empty($corpTagIds)) {
                $scheme->corpTags()->detach();
            } else {
                $scheme->corpTags()->sync(array_unique($corpTagIds));
            }

            if (empty($smartTagIds)) {
                $scheme->corpTags()->detach();
            } else {
                $scheme->smartTags()->sync(array_unique($smartTagIds));
            }
            return true;
        }
        return false;
    }

    /**
     * 批量真实删除方案.
     */
    #[Transaction]
    public function deleteScheme(mixed $id): bool
    {
        $robotSchemeMapper = container()->get(ChOpSchemeRobotMapper::class);
        $scheme = $this->model::query()->find($id);
        if ($scheme) {
            // 删除关键词
            $scheme->keywords()->delete();
            //删除企业标签
            $scheme->corpTags()->detach();
            //删除智能标签
            $scheme->smartTags()->detach();
            //删除方案于企微号的关联
            $robotSchemeMapper->deleteBySchemeIdAndType($id,OpSchemeTypeConstants::KEYWORD_TAG);
            $scheme->delete();
        }
        return true;
    }
}